class DocumentsController < ApplicationController
	
	include SortHelper
	
	helper_method :sort_options
	skip_before_filter :require_logged_in, only: [:index, :show]
	
	def index
		@documents = Document.with_translations
			.order(sort_order('name', Document))
			.paginate(page: params[:page])
			.all
	end
	
	# Document Detail page
	def show
		@document = Document.find(params[:id])
		@new_comment = @document.comments.build
		
		if permissible?('index', nil, 'Comments')
			@comments = @document.comments
		else
			@comments = []
		end
		@comments = @comments.paginate(page: params[:page])
	end
    
    def new
        @document = Document.new
		@traceability_action = :created_by
		@all_categories = indented_options(Category.scoped.arrange(order: :order_position))
		@selected_categories = @document.categories.map { |cat| cat.id }
		@tags = ''
    end
    
    def create
		params[:document][:owner] = current_user
		params[:document][:categories] = Category.find(params[:category_ids]) unless params[:category_ids].blank?
		
		@document = Document.create_with_default_permissions(params[:document])
		
		if @document.errors.any?
            @errors = @document.errors
			@traceability_action = :created_by
			@all_categories = indented_options(Category.scoped.arrange(order: :order_position))
			@selected_categories = @document.categories.map { |cat| cat.id }
			@tags = Tag.tags_to_string(@document.tags)
			render 'new'
		else
			redirect_to @document, flash: { success: t('document.create.success') }
		end
    end
	
	def edit
		@document = Document.find(params[:id])
		@traceability_action = :updated_by
		@all_categories = indented_options(Category.scoped.arrange(order: :order_position))
		@selected_categories = @document.categories.collect { |cat| cat.id }
		@tags = Tag.tags_to_string(@document.tags)
	end
	
	def update
		@document = Document.find(params[:id])
		
		@document.categories = Category.find(params[:category_ids])
		params[:document][:tags] = Tag.string_to_tags(params[:document][:tags], current_user, @document)
		
		if @document.update_attributes(params[:document])
			redirect_to @document, flash: { success: t('document.update.success') }
		else
            @errors = @document.errors
			render 'edit'
		end
	end
	
	def destroy
		document = Document.find(params[:id])
		document.remove
		redirect_to archive_path, flash: { success: t('document.destroy.success') }
	end

	private 
	
	def sort_options
		AComposite.sort_options
	end
    
end
